package com.yunchen.server.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yunchen.server.pojo.Users;
import com.yunchen.server.service.UsersService;
import com.yunchen.server.util.MyUtil;
import com.yunchen.server.util.Return;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RequestMapping("/Users")
@RestController
@Transactional
@CrossOrigin
public class UsersController {
    @Autowired
    private UsersService usersService;
    @PostMapping("/Login")
    public Return Login(@RequestBody Users users,HttpServletRequest request){
        Return re = new Return();
        try {
            re= usersService.Login(users,request);
        }catch  (Exception e) {
            e.printStackTrace();
            re.setCode(400);
            re.setMsg("操作失败");
        }
        return re;
    }

    @PostMapping("/Add")
    public Return Add(@RequestBody JSONObject json){
        Return re = new Return();
        if(MyUtil.isEmpty(json)){
            re.setMsg("传参数有误");
            re.setCode(400);
            return re;
        }
        try {
            re= usersService.Add(json);
        }catch  (Exception e) {
            e.printStackTrace();
            re.setCode(400);
            re.setMsg("操作失败");
        }
        return re;
    }

    @PostMapping("/List")
    public Return List(@RequestBody JSONObject json){
        Return re = new Return();
        if(MyUtil.isEmpty(json)){
            re.setMsg("传参数有误");
            re.setCode(400);
            return re;
        }
        try {
            Integer count = usersService.Count(json);
            JSONArray list = usersService.List(json);
            re.setData(list);
            re.setMaxPage(count);
            re.setCode(200);
            re.setMsg("成功");
        }catch  (Exception e) {
            e.printStackTrace();
            re.setCode(400);
            re.setMsg("操作失败");
        }
        return re;
    }
    @PostMapping("/del")
    public Return del(@RequestBody JSONObject json){
        Return re = new Return();
        if(MyUtil.isEmpty(json)){
            re.setMsg("传参数有误");
            re.setCode(400);
            return re;
        }
        try {
            re= usersService.del(json);
        }catch  (Exception e) {
            e.printStackTrace();
            re.setCode(400);
            re.setMsg("操作失败");
        }
        return re;
    }

}
